package com.basic.modules.ykf.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.basic.common.exception.RRException;
import com.basic.common.utils.*;
import com.basic.modules.sys.service.SysUserService;
import com.basic.modules.ykf.dao.YkfCustomerShopDao;
import com.basic.modules.ykf.entity.*;
import com.basic.modules.ykf.model.*;
import com.basic.modules.ykf.service.*;
import com.basic.modules.ykf.utils.ExcelCellWidthStyleStrategy;
import com.basic.modules.ykf.utils.ExcelStyleUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.basic.modules.ykf.dao.YkfCustomerDao;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;


@Service("ykfCustomerService")
public class YkfCustomerServiceImpl extends ServiceImpl<YkfCustomerDao, YkfCustomerEntity> implements YkfCustomerService {

    @Autowired
    private YkfCustomerShopDao shopDao;

    @Lazy
    @Autowired
    private YkfCustomerShopService customerShopService;

    @Autowired
    private SysUserService userService;

    @Lazy
    @Autowired
    private YkfAccountInputRecordService inputRecordService;

    @Lazy
    @Autowired
    private YkfCustomerSubAccountService subAccountService;

    @Autowired
    private YkfDictService dictService;

    @Autowired
    private YkfDictDetailService dictDetailService;

    @Override
    public PageUtils queryPage(ParamsModel<YkfCustomerShopEntity> params) {
        IPage<YkfCustomerShopEntity> page1 = new Query<YkfCustomerShopEntity>().getPage(BeanUtil.beanToMap(params.getPage()));
        //过滤创建人
//        List<Long> powerUserIds = userService.getPowerUserIds();
//        params.getCondition().setCreateUserIds(powerUserIds);
//        SysUserEntity user = CommonUtils.getUser();
//        if (user.getUserId() != Constant.SUPER_ADMIN) {
//            //【岗位】市场专员，只能看到自己的新增的数据；续费专员可以看全部的数据；市场经理，市场总监可以看全部的数据
//            if (StrUtil.equalsAny(user.getPostNo(), "市场专员", "续费专员", "市场部总监", "市场部经理", "总经理", "副总经理", "董事长", "副董事长")) {
//                if (StrUtil.equals(user.getPostNo(), "市场专员")) {
//                    params.getCondition().setCreateUserId(user.getUserId());
//                }
//            } else {
//                IPage iPage = new Page();
//                iPage.setTotal(0);
//                iPage.setPages(0);
//                iPage.setRecords(new ArrayList());
//                return new PageUtils(iPage);
//            }
        //过滤客户
        //过滤店铺
//        }
        //过滤店铺权限
//        List<Long> powerCustomerShopIds = userService.getPowerCustomerShopIds();
        List<Long> powerCustomerShopIds = userService.getOneselfPowerCustomerShopIds();
        boolean oneselfFlag = userService.getOneselfFlag();
        params.getCondition().setOneSelfFlag(oneselfFlag);
        if (oneselfFlag) {
            params.getCondition().setCreateUserId(CommonUtils.getUserId());
        }
        if (ObjectUtil.isEmpty(powerCustomerShopIds)) {
            if (!oneselfFlag) {
                return new PageUtils();
            }
        } else {
            // 如果店铺集合不包含0,才给店铺ID的条件查询,否则直接就是查所有数据了
            if (!powerCustomerShopIds.contains(0L)) {
                params.getCondition().setPowerShopIds(powerCustomerShopIds);
            }
        }

        if (ObjectUtil.isNotEmpty(params.getCondition()) && ObjectUtil.isNotEmpty(params.getCondition().getStopDays())) {
            //按照当天日期往前推算日期
            DateTime dateTime = DateUtil.offsetDay(DateUtil.date(), params.getCondition().getStopDays());
            params.getCondition().setEndDate(dateTime);
        }
//        params.getPage().setStartPos((params.getPage().getIndex() - 1) * params.getPage().getSize());

        params.getCondition().setToday(DateUtil.today());
        params.getCondition().setCustomerCooperateStatus(1);
        //客户等级排序
        if (ObjectUtil.isNotEmpty(params.getSort())
                && StrUtil.isNotBlank(params.getSort().getOrder())
                && StrUtil.isNotBlank(params.getSort().getSidx())
                && StrUtil.equals(params.getSort().getSidx(), "customerLvl")) {
            //查询所有店铺的客户等级
            List<YkfCustomerShopEntity> shopList = shopDao.getShopList(ObjectUtil.isEmpty(params.getCondition()) ? new YkfCustomerShopEntity() : params.getCondition(), params.getSort());
            if (ObjectUtil.isNotEmpty(shopList)) {
                for (YkfCustomerShopEntity record : shopList) {
                    extracted(record);
                }
                if (StrUtil.equals(params.getSort().getOrder(), "desc")) {
                    shopList.sort(Comparator.comparing(YkfCustomerShopEntity::getCustomerLvl).reversed());
                } else {
                    shopList.sort(Comparator.comparing(YkfCustomerShopEntity::getCustomerLvl));
                }
//                LinkedHashMap<Long, List<YkfCustomerShopEntity>> linkedHashMap = new LinkedHashMap<>();
                List<Long> customerIds = new ArrayList<>();
                for (YkfCustomerShopEntity shop : shopList) {
                    if (ObjectUtil.isEmpty(shop.getMarketTypeNo())) {
                        shop.setMarketTypeNo("");
                        shop.setMarketTypeName("");
                    }
//                    if (!customerIds.contains(shop.getCustomerId())) {
//                        List<YkfCustomerShopEntity> list = new ArrayList<>();
//                        list.add(shop);
//                        linkedHashMap.put(shop.getCustomerId(), list);
//                        customerIds.add(shop.getCustomerId());
//                    } else {
//                        linkedHashMap.get(shop.getCustomerId()).add(shop);
//                    }
                }

                LinkedHashMap<Long, List<YkfCustomerShopEntity>> collect = shopList.stream()
                        .collect(Collectors.groupingBy(YkfCustomerShopEntity::getCustomerId,LinkedHashMap::new,Collectors.toList()));
                List<YkfCustomerEntity> customerEntityList = new ArrayList<>();
                for (Long id : collect.keySet()) {
                    YkfCustomerEntity item = this.getById(id);
                    LinkedHashMap<String, List<YkfCustomerShopEntity>> collect1 = collect.get(id).stream()
                            .collect(Collectors.groupingBy(YkfCustomerShopEntity::getMarketTypeNo,LinkedHashMap::new,Collectors.toList()));
                    List<YkfCustomerEntity> bodyList = new ArrayList<>();
                    for (String markType : collect1.keySet()) {
                        YkfCustomerEntity item2 = new YkfCustomerEntity();
                        item2.setShopList(collect1.get(markType));
                        bodyList.add(item2);
                    }
                    item.setBodyList(bodyList);
                    customerEntityList.add(item);
                }

                //结果分页
                IPage<YkfCustomerEntity> page = new Query<YkfCustomerEntity>().getPage(BeanUtil.beanToMap(params.getPage()));
//                int totalcount = customerIds.size();
                int totalcount = customerEntityList.size();
                Long size = params.getPage().getSize();
                Long current = params.getPage().getIndex();
                page.setTotal(totalcount);
                long pagecount = 0;
                long m = totalcount % size;
                if (m > 0) {
                    pagecount = totalcount / size + 1;
                } else {
                    pagecount = totalcount / size;
                }
                page.setPages(pagecount);
//                if (m == 0) {
//                    customerIds = customerIds.subList((int) ((current - 1) * size), (int) (size * (current)));
//                } else {
//                    if (current == pagecount) {
//                        customerIds = customerIds.subList((int) ((current - 1) * size), (int) totalcount);
//                    } else {
//                        customerIds =  customerIds.subList((int) ((current - 1) * size), (int) (size * (current)));
//                    }
//                }
                if (m == 0) {
                    customerEntityList = customerEntityList.subList((int) ((current - 1) * size), (int) (size * (current)));
                } else {
                    if (current == pagecount) {
                        customerEntityList = customerEntityList.subList((int) ((current - 1) * size), (int) totalcount);
                    } else {
                        customerEntityList =  customerEntityList.subList((int) ((current - 1) * size), (int) (size * (current)));
                    }
                }
//                List<YkfCustomerEntity> entityList = new ArrayList<>();
//                for (Long l : customerIds) {
//                    YkfCustomerEntity customer = new YkfCustomerEntity();
//                    List<YkfCustomerShopEntity> list = linkedHashMap.get(l);
//                    BeanUtil.copyProperties(list.get(0), list.get(0));
//                    customer.setShopList(list);
//                    entityList.add(customer);
//                }
                page.setRecords(customerEntityList);
                page.setSize(size);
                page.setCurrent(current);
                return new PageUtils(page);
            }
            return new PageUtils();
        } else {
            IPage<Long> customerPage = shopDao.getCustomerPage(page1, params.getSort(), ObjectUtil.isEmpty(params.getCondition()) ? new YkfCustomerShopEntity() : params.getCondition());
            if (ObjectUtil.isNotEmpty(customerPage) && ObjectUtil.isNotEmpty(customerPage.getRecords())) {
                List<Long> customerIds = customerPage.getRecords();
                params.getCondition().setCustomerIds(customerIds);
            } else {
                return new PageUtils();
            }
            //        IPage<YkfCustomerShopEntity> shopPage = shopDao.getShopPage(page, params.getSort(), ObjectUtil.isEmpty(params.getCondition()) ? new YkfCustomerShopEntity() : params.getCondition());

            List<YkfCustomerShopEntity> shopList = shopDao.getShopList(ObjectUtil.isEmpty(params.getCondition()) ? new YkfCustomerShopEntity() : params.getCondition(), params.getSort());
            //汇总
            if (ObjectUtil.isNotEmpty(shopList)) {

                for (YkfCustomerShopEntity shop : shopList) {
                    extracted(shop);
                    if (ObjectUtil.isEmpty(shop.getMarketTypeNo())) {
                        shop.setMarketTypeNo("");
                        shop.setMarketTypeName("");
                    }
                }
                LinkedHashMap<Long, List<YkfCustomerShopEntity>> collect = shopList.stream()
                        .collect(Collectors.groupingBy(YkfCustomerShopEntity::getCustomerId,LinkedHashMap::new,Collectors.toList()));
                List<YkfCustomerEntity> customerEntityList = new ArrayList<>();
                for (Long id : collect.keySet()) {
                    YkfCustomerEntity item = this.getById(id);
                    LinkedHashMap<String, List<YkfCustomerShopEntity>> collect1 = collect.get(id).stream()
                            .collect(Collectors.groupingBy(YkfCustomerShopEntity::getMarketTypeNo,LinkedHashMap::new,Collectors.toList()));
                    List<YkfCustomerEntity> bodyList = new ArrayList<>();
                    for (String markType : collect1.keySet()) {
                        YkfCustomerEntity item2 = new YkfCustomerEntity();
                        item2.setShopList(collect1.get(markType));
                        bodyList.add(item2);
                    }
                    item.setBodyList(bodyList);
                    customerEntityList.add(item);
                }
//                LinkedHashMap<Long, List<YkfCustomerShopEntity>> collect = new LinkedHashMap<>();
//                for (YkfCustomerShopEntity record : shopList) {
//                    extracted(record);
//                    if (collect.containsKey(record.getCustomerId())) {
//                        List<YkfCustomerShopEntity> list = collect.get(record.getCustomerId());
//                        list.add(record);
//                        collect.put(record.getCustomerId(), list);
//                    } else {
//                        List<YkfCustomerShopEntity> list = new ArrayList<>();
//                        list.add(record);
//                        collect.put(record.getCustomerId(), list);
//                    }
//                }
//            Map<Long, List<YkfCustomerShopEntity>> collect = shopPage.getRecords().stream().collect(Collectors.groupingBy(YkfCustomerShopEntity::getCustomerId));
//                List<YkfCustomerEntity> customerEntityList = new ArrayList<>();
//                for (Long id : collect.keySet()) {
//                    YkfCustomerEntity item = this.getById(id);
//                    item.setShopList(collect.get(id));
//                    customerEntityList.add(item);
//                }
                IPage<YkfCustomerEntity> resPage = new Query<YkfCustomerEntity>().getPage(BeanUtil.beanToMap(params.getPage()));
                resPage.setPages(customerPage.getPages());
                resPage.setTotal(customerPage.getTotal());
                resPage.setSize(customerPage.getSize());
                resPage.setCurrent(customerPage.getCurrent());
                resPage.setRecords(customerEntityList);
                return new PageUtils(resPage);
            }
            return new PageUtils(customerPage);
        }
    }

    private void extracted(YkfCustomerShopEntity record) {
        //计算客户等级
        int score1 = 0;
        int score2 = 0;
        int score3 = 0;
        int score4 = 0;
        //店铺难度得分
        String shopTypeName = record.getShopTypeName();
        if (StrUtil.isNotBlank(shopTypeName)) {
            if (shopTypeName.contains("简单")) {
                score1 = 24;
            } else if (shopTypeName.contains("普通")) {
                score1 = 18;
            } else if (shopTypeName.contains("困难")) {
                score1 = 12;
            } else if (shopTypeName.contains("噩梦")) {
                score1 = 6;
            }
        }
        //服务天数得分
        if (ObjectUtil.isNotEmpty(record.getStartDate())) {
            Date start = record.getStartDate();
            DateTime date = DateUtil.date();
            if (start.compareTo(date) < 0) {
                long days = DateUtil.betweenDay(start, date, false);
                if (days >= 180) {
                    score2 = 24;
                } else if (days >= 90) {
                    score2 = 18;
                } else if (days >= 60) {
                    score2 = 12;
                } else if (days >= 30) {
                    score2 = 6;
                }
            }
        }
        //配合度得分
        if (StrUtil.isNotBlank(record.getFitRatioNo())) {
            switch (record.getFitRatioNo()) {
                case "D":
                    score3 = 12;
                    break;
                case "C":
                    score3 = 9;
                    break;
                case "B":
                    score3 = 6;
                    break;
                case "A":
                    score3 = 3;
                    break;
            }
        }
        //效益得分 上个服务开始时间 上个服务结束时间 上个服务周期总收益 上个服务周期总接待人数 上个服务周期日均接待人数 上个服务周期效益占比
        if (ObjectUtil.isNotEmpty(record.getStartDate())) {
            DateTime end = DateUtil.offsetDay(record.getStartDate(), -1);
            DateTime start = DateUtil.offsetDay(end, -30);
            Map<String, BigDecimal> map = shopBenefit(start, end, record);
            BigDecimal sumSalary = map.get("sumSalary");
            BigDecimal averageReceptionVolume = map.get("averageReceptionVolume");
            List<YkfDictDetailEntity> dayRnumRatio = searchDictDetail("dayRnumRatio");
            try {
                if (ObjectUtil.isNotEmpty(dayRnumRatio)) {
                    BigDecimal value = BigDecimal.ONE;
                    for (YkfDictDetailEntity detail : dayRnumRatio) {
                        List<String> split = StrUtil.split(detail.getName(), '-');
                        if (split.size() == 2) {
                            BigDecimal decimal1 = new BigDecimal(split.get(0));
                            BigDecimal decimal2 = new BigDecimal(split.get(1));
                            if (averageReceptionVolume.compareTo(decimal1) >= 0
                                    && averageReceptionVolume.compareTo(decimal2) <= 0) {
                                value = new BigDecimal(detail.getVal());
                                break;
                            }
                        }
                    }
                    //计算上个服务效益占比
                    BigDecimal divide = sumSalary.multiply(new BigDecimal(100)).divide(value, 0, RoundingMode.HALF_DOWN);
                    List<YkfDictDetailEntity> benefitRatio = searchDictDetail("benefitRatio");
                    if (ObjectUtil.isNotEmpty(benefitRatio)) {
                        benefitRatio.sort(Comparator.comparing(YkfDictDetailEntity::getVal).reversed());
                        for (YkfDictDetailEntity detail : benefitRatio) {
                            if (StrUtil.equals(detail.getVal(), "160") && divide.compareTo(new BigDecimal(detail.getVal())) >= 0) {
                                score4 = 40;
                            }
                            if (StrUtil.equals(detail.getVal(), "130") && divide.compareTo(new BigDecimal(detail.getVal())) >= 0) {
                                score4 = 20;
                            }
                            if (StrUtil.equals(detail.getVal(), "100") && divide.compareTo(new BigDecimal(detail.getVal())) >= 0) {
                                score4 = 10;
                            }
                            if (StrUtil.equals(detail.getVal(), "0") && divide.compareTo(new BigDecimal(detail.getVal())) >= 0) {
                                score4 = 5;
                            }
                        }
                    }
                }
            } catch (Exception e) {
                log.error(e.getMessage());
            }
        }
        int sumScore = score1 + score2 + score3 + score4;
        if (sumScore >= 80) {
            record.setCustomerLvl("A");
        } else if (sumScore >= 60) {
            record.setCustomerLvl("B");
        } else if (sumScore >= 40) {
            record.setCustomerLvl("C");
        } else {
            record.setCustomerLvl("D");
        }
    }

    public List<YkfDictDetailEntity> searchDictDetail(String dictNo) {
        QueryWrapper<YkfDictEntity> dictQueryWrapper = new QueryWrapper<>();
        dictQueryWrapper.lambda().eq(YkfDictEntity::getDictNo, dictNo);
        dictQueryWrapper.last("limit 1");
        YkfDictEntity dict = dictService.getOne(dictQueryWrapper);
        if (ObjectUtil.isNotEmpty(dict)) {
            QueryWrapper<YkfDictDetailEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(YkfDictDetailEntity::getDictId, dict.getDictId())
                    .orderByAsc(YkfDictDetailEntity::getSort);
            List<YkfDictDetailEntity> list = dictDetailService.list(queryWrapper);
            return list;
        }
        return new ArrayList<>();
    }

    @Override
    public PageUtils shopBenefitPage(ParamsModel<YkfCustomerShopEntity> params) {
        IPage<YkfCustomerShopEntity> page = new Query<YkfCustomerShopEntity>().getPage(BeanUtil.beanToMap(params.getPage()));
        //过滤创建人
//        SysUserEntity user = CommonUtils.getUser();
//        if (user.getUserId() != Constant.SUPER_ADMIN) {
//            //【岗位】市场专员，只能看到自己的新增的数据；续费专员可以看全部的数据；市场经理，市场总监可以看全部的数据
//            if (StrUtil.equalsAny(user.getPostNo(), "市场专员", "续费专员", "市场部总监", "市场部经理", "总经理", "副总经理", "董事长", "副董事长")) {
//                if (StrUtil.equals(user.getPostNo(), "市场专员")) {
//                    params.getCondition().setCreateUserId(user.getUserId());
//                }
//            } else {
//                IPage iPage = new Page();
//                iPage.setTotal(0);
//                iPage.setPages(0);
//                iPage.setRecords(new ArrayList());
//                return new PageUtils(iPage);
//            }
//        }
//        params.getPage().setStartPos((params.getPage().getIndex() - 1) * params.getPage().getSize());
//        List<Long> powerCustomerShopIds = userService.getPowerCustomerShopIds();
        List<Long> powerCustomerShopIds = userService.getOneselfPowerCustomerShopIds();
        if (ObjectUtil.isNotEmpty(powerCustomerShopIds)) {
            if (!powerCustomerShopIds.contains(0L)) {
                YkfCustomerShopEntity condition = params.getCondition();
                if (ObjectUtil.isNull(params.getCondition())) {
                    condition = new YkfCustomerShopEntity();
                }
                params.getCondition().setPowerShopIds(powerCustomerShopIds);
                params.setCondition(condition);
            }
        } else {
            return new PageUtils();
        }
        if (ObjectUtil.isNotEmpty(params.getCondition().getMonth())) {
            DateTime parse = DateUtil.parse(params.getCondition().getMonth(), "yyyy-MM");
            DateTime startDay = DateUtil.beginOfMonth(parse);
            DateTime endDay = DateUtil.endOfMonth(parse);
            params.getCondition().setStartDate(startDay);
            params.getCondition().setEndDate(endDay);
        }
        if (ObjectUtil.isNotEmpty(params.getCondition().getStopDays()) && params.getCondition().getStopDays() > 0) {
            //按照当天日期往前推算日期
            DateTime dateTime = DateUtil.offsetDay(DateUtil.date(), params.getCondition().getStopDays());
            params.getCondition().setEndDate(dateTime);
        }
        IPage<Long> customerPage = shopDao.getCustomerPage2(page, params.getSort(), ObjectUtil.isEmpty(params.getCondition()) ? new YkfCustomerShopEntity() : params.getCondition());
        List<YkfCustomerShopEntity> shopListSum = shopDao.getShopPage2(params.getSort(), ObjectUtil.isEmpty(params.getCondition()) ? new YkfCustomerShopEntity() : params.getCondition());

        Map<String, Object> map = new HashMap<>();
        map.put("commissionSalary", BigDecimal.ZERO);
        map.put("baseSalary", BigDecimal.ZERO);
        map.put("sumSalary", BigDecimal.ZERO);
        if (ObjectUtil.isNotEmpty(shopListSum)) {
            BigDecimal commissionSalary = BigDecimal.ZERO;
            BigDecimal sumSalary = BigDecimal.ZERO;
            BigDecimal baseSalary = BigDecimal.ZERO;
            for (YkfCustomerShopEntity shopEntity : shopListSum) {
                //合作天数
                if (ObjectUtil.isNotEmpty(shopEntity.getStartDate())) {
                    DateTime date = DateUtil.date();
                    Date beginOfMonth = params.getCondition().getStartDate();
                    if (ObjectUtil.isEmpty(shopEntity.getEndDate()) || ObjectUtil.compare(date, shopEntity.getEndDate()) < 0) {
                        shopEntity.setWorkDays((int) DateUtil.betweenDay(beginOfMonth, date, false) + 1);
                        shopEntity.setCooperateDays((int) DateUtil.betweenDay(shopEntity.getStartDate(), date, false) + 1);
                    } else {
                        shopEntity.setWorkDays((int) DateUtil.betweenDay(beginOfMonth, shopEntity.getEndDate(), false) + 1);
                        shopEntity.setCooperateDays((int) DateUtil.betweenDay(shopEntity.getStartDate(), shopEntity.getEndDate(), false) + 1);
                    }
                } else {
                    shopEntity.setWorkDays(0);
                    shopEntity.setCooperateDays(0);
                }
                BigDecimal l = new BigDecimal(DateUtil.betweenDay(params.getCondition().getStartDate(), params.getCondition().getEndDate(), false));
                shopEntity.setBaseSalary(new BigDecimal(shopEntity.getWorkDays()).multiply(shopEntity.getBaseSalary()).divide((l.add(BigDecimal.ONE)), 2, RoundingMode.HALF_UP));
                if (ObjectUtil.isNotEmpty(shopEntity.getCommission())) {
                    //查询总销售额
                    QueryWrapper<YkfAccountInputRecordEntity> inputRecordQueryWrapper = new QueryWrapper<>();
                    inputRecordQueryWrapper.lambda().eq(YkfAccountInputRecordEntity::getShopId, shopEntity.getShopId())
                            .ge(YkfAccountInputRecordEntity::getDate, params.getCondition().getStartDate())
                            .le(YkfAccountInputRecordEntity::getDate, params.getCondition().getEndDate());
                    List<YkfAccountInputRecordEntity> list = inputRecordService.list(inputRecordQueryWrapper);
                    BigDecimal sum = BigDecimal.ZERO;
                    if (ObjectUtil.isNotEmpty(list)) {
                        for (YkfAccountInputRecordEntity recordEntity : list) {
                            if (ObjectUtil.isNotEmpty(recordEntity.getSalesRevenue())) {
                                sum = sum.add(recordEntity.getSalesRevenue());
                            }
                        }
                    }
                    commissionSalary = commissionSalary.add(sum.multiply(shopEntity.getCommission()).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP));
                }
                sumSalary = sumSalary.add(NumberUtil.add(shopEntity.getBaseSalary(), shopEntity.getCommissionSalary()));
                baseSalary = NumberUtil.add(baseSalary, shopEntity.getBaseSalary());
            }
            map.put("commissionSalary", commissionSalary);
            map.put("baseSalary", baseSalary);
            map.put("sumSalary", commissionSalary.add(baseSalary));
        }

        if (ObjectUtil.isNotEmpty(customerPage)) {
            List<Long> customerIds = customerPage.getRecords();
            params.getCondition().setCustomerIds(customerIds);
        }
        List<YkfCustomerShopEntity> shopList = shopDao.getShopPage2(params.getSort(), ObjectUtil.isEmpty(params.getCondition()) ? new YkfCustomerShopEntity() : params.getCondition());

        //汇总
        if (ObjectUtil.isNotEmpty(shopList)) {
            Map<Long, List<YkfCustomerShopEntity>> collect = shopList.stream().collect(Collectors.groupingBy(YkfCustomerShopEntity::getCustomerId));
            List<YkfCustomerEntity> customerEntityList = new ArrayList<>();
            for (Long id : collect.keySet()) {
                YkfCustomerEntity item = this.getById(id);
                //计算客户合计值
                BigDecimal customBaseSalary = BigDecimal.ZERO;
                Integer customDayReceptionVolume = 0;
                BigDecimal customCommissionSalary = BigDecimal.ZERO;
                BigDecimal customMonthSalary = BigDecimal.ZERO;
                BigDecimal customSumSalary = BigDecimal.ZERO;
                for (YkfCustomerShopEntity shopEntity : collect.get(id)) {
                    if (ObjectUtil.isNotEmpty(shopEntity.getCommission())) {
                        //查询总销售额
                        QueryWrapper<YkfAccountInputRecordEntity> inputRecordQueryWrapper = new QueryWrapper<>();
                        inputRecordQueryWrapper.lambda().eq(YkfAccountInputRecordEntity::getShopId, shopEntity.getShopId())
                                .ge(YkfAccountInputRecordEntity::getDate, params.getCondition().getStartDate())
                                .le(YkfAccountInputRecordEntity::getDate, params.getCondition().getEndDate());
                        List<YkfAccountInputRecordEntity> list = inputRecordService.list(inputRecordQueryWrapper);
                        BigDecimal sum = BigDecimal.ZERO;
                        if (ObjectUtil.isNotEmpty(list)) {
                            for (YkfAccountInputRecordEntity recordEntity : list) {
                                if (ObjectUtil.isNotEmpty(recordEntity.getSalesRevenue())) {
                                    sum = sum.add(recordEntity.getSalesRevenue());
                                }
                            }
                        }
                        BigDecimal commissionSalary = sum.multiply(shopEntity.getCommission()).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP);
                        shopEntity.setCommissionSalary(commissionSalary);
                    } else {
                        shopEntity.setCommissionSalary(BigDecimal.ZERO);
                    }
                    if (ObjectUtil.isNotEmpty(shopEntity.getStartDate())) {
                        DateTime date = DateUtil.date();
                        Date beginOfMonth = params.getCondition().getStartDate();
                        if (ObjectUtil.isEmpty(shopEntity.getEndDate()) || ObjectUtil.compare(date, shopEntity.getEndDate()) < 0) {
                            shopEntity.setWorkDays((int) DateUtil.betweenDay(beginOfMonth, date, false) + 1);
                            shopEntity.setCooperateDays((int) DateUtil.betweenDay(shopEntity.getStartDate(), date, false) + 1);
                        } else {
                            shopEntity.setWorkDays((int) DateUtil.betweenDay(beginOfMonth, shopEntity.getEndDate(), false) + 1);
                            shopEntity.setCooperateDays((int) DateUtil.betweenDay(shopEntity.getStartDate(), shopEntity.getEndDate(), false) + 1);
                        }
                    } else {
                        shopEntity.setWorkDays(0);
                        shopEntity.setCooperateDays(0);
                    }
                    BigDecimal l = new BigDecimal(DateUtil.betweenDay(params.getCondition().getStartDate(), params.getCondition().getEndDate(), false));
                    //计算月效益预估
                    BigDecimal add = l
                            .multiply(shopEntity.getCommissionSalary())
                            .divide(new BigDecimal(shopEntity.getWorkDays()), 2, RoundingMode.HALF_UP)
                            .add(shopEntity.getBaseSalary());
                    shopEntity.setMonthSalary(add);
                    shopEntity.setBaseSalary(new BigDecimal(shopEntity.getWorkDays()).multiply(shopEntity.getBaseSalary()).divide((l.add(BigDecimal.ONE)), 2, RoundingMode.HALF_UP));

                    shopEntity.setMonth(params.getCondition().getMonth());
                    shopEntity.setSumSalary(NumberUtil.add(shopEntity.getBaseSalary(), shopEntity.getCommissionSalary()));


                    //日均咨询量
                    QueryWrapper<YkfAccountInputRecordEntity> queryWrapper = new QueryWrapper<>();
                    queryWrapper.lambda().eq(YkfAccountInputRecordEntity::getShopId, shopEntity.getShopId());
                    List<YkfAccountInputRecordEntity> list = inputRecordService.list(queryWrapper);
                    BigDecimal sum = BigDecimal.ZERO;
                    if (ObjectUtil.isNotEmpty(list)) {
                        for (YkfAccountInputRecordEntity recordEntity : list) {
                            sum = sum.add(recordEntity.getReceptionVolume());
                        }
                    }
                    if (shopEntity.getWorkDays() > 0) {
                        shopEntity.setDayReceptionVolume(sum.divide(new BigDecimal(shopEntity.getWorkDays()), 0, RoundingMode.HALF_UP).intValue());
                    } else {
                        shopEntity.setDayReceptionVolume(0);
                    }

                    customBaseSalary = customBaseSalary.add(shopEntity.getBaseSalary());
                    customDayReceptionVolume = customDayReceptionVolume + shopEntity.getDayReceptionVolume();
                    customCommissionSalary = customCommissionSalary.add(shopEntity.getCommissionSalary());
                    customMonthSalary = customMonthSalary.add(shopEntity.getMonthSalary());
                    customSumSalary = customSumSalary.add(shopEntity.getSumSalary());
                }
                item.setShopList(collect.get(id));
                item.setCustomBaseSalary(customBaseSalary);
                item.setCustomDayReceptionVolume(customDayReceptionVolume);
                item.setCustomCommissionSalary(customCommissionSalary);
                item.setCustomMonthSalary(customMonthSalary);
                item.setCustomSumSalary(customSumSalary);
                customerEntityList.add(item);
            }
            IPage<YkfCustomerEntity> resPage = new Query<YkfCustomerEntity>().getPage(BeanUtil.beanToMap(params.getPage()));
            resPage.setPages(customerPage.getPages());
            resPage.setTotal(customerPage.getTotal());
            resPage.setSize(customerPage.getSize());
            resPage.setCurrent(customerPage.getCurrent());
            resPage.setRecords(customerEntityList);
            return new PageUtils(resPage, map);
        }
        return new PageUtils(map);
    }

    public static int getTotalMonthDate(Date date) {
        if (date == null)
            return 0;
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.DATE, 1);// 把日期设置为当月第一天
        calendar.roll(Calendar.DATE, -1);// 日期回滚一天，也就是最后一天
        return calendar.get(Calendar.DATE);
    }

    @Override
    public Map<String, BigDecimal> shopBenefit(Date start, Date end, YkfCustomerShopEntity shop) {
        Map<String, BigDecimal> map = new HashMap<>();
        map.put("sumSalary", BigDecimal.ZERO);
        map.put("sumReceptionVolume", BigDecimal.ZERO);
        map.put("averageReceptionVolume", BigDecimal.ZERO);
        if (ObjectUtil.isNotEmpty(shop.getCommission())) {
            //查询总销售额
            QueryWrapper<YkfAccountInputRecordEntity> inputRecordQueryWrapper = new QueryWrapper<>();
            inputRecordQueryWrapper.lambda().eq(YkfAccountInputRecordEntity::getShopId, shop.getShopId())
                    .ge(YkfAccountInputRecordEntity::getDate, start)
                    .le(YkfAccountInputRecordEntity::getDate, end);
            List<YkfAccountInputRecordEntity> list = inputRecordService.list(inputRecordQueryWrapper);
            BigDecimal sum = BigDecimal.ZERO;
            BigDecimal sumReceptionVolume = BigDecimal.ZERO;
            if (ObjectUtil.isNotEmpty(list)) {
                for (YkfAccountInputRecordEntity recordEntity : list) {
                    if (ObjectUtil.isNotEmpty(recordEntity.getSalesRevenue())) {
                        sum = sum.add(recordEntity.getSalesRevenue());
                        sumReceptionVolume = sumReceptionVolume.add(recordEntity.getReceptionVolume());
                    }
                }
                BigDecimal commissionSalary = sum.multiply(shop.getCommission()).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP);
                BigDecimal sumSalary = NumberUtil.add(shop.getBaseSalary(), commissionSalary);
                BigDecimal averageReceptionVolume = sumReceptionVolume.divide(new BigDecimal(DateUtil.betweenDay(start, end, false) + 1), 0, RoundingMode.HALF_UP);
                map.put("sumSalary", sumSalary);
                map.put("sumReceptionVolume", sumReceptionVolume);
                map.put("averageReceptionVolume", averageReceptionVolume);
            }
        }
        return map;
    }

    @Override
    public PageUtils queryStopPage(ParamsModel<YkfCustomerShopEntity> params) {
        IPage<YkfCustomerShopEntity> page = new Query<YkfCustomerShopEntity>().getPage(BeanUtil.beanToMap(params.getPage()));
        //过滤创建人
//        SysUserEntity user = CommonUtils.getUser();
//        if (user.getUserId() != Constant.SUPER_ADMIN) {
//            //【岗位】市场专员，只能看到自己的新增的数据；续费专员可以看全部的数据；市场经理，市场总监可以看全部的数据
//            if (StrUtil.equalsAny(user.getPostNo(), "市场专员", "续费专员", "市场部总监", "市场部经理", "总经理", "副总经理", "董事长", "副董事长")) {
//                if (StrUtil.equals(user.getPostNo(), "市场专员")) {
//                    params.getCondition().setCreateUserId(user.getUserId());
//                }
//            } else {
//                IPage iPage = new Page();
//                iPage.setTotal(0);
//                iPage.setPages(0);
//                iPage.setRecords(new ArrayList());
//                return new PageUtils(iPage);
//            }
//        }
//        if (ObjectUtil.isNotEmpty(params.getCondition().getStopDays()) && params.getCondition().getStopDays() > 0) {
//            //按照当天日期往前推算日期
//            DateTime dateTime = DateUtil.offsetDay(DateUtil.date(), params.getCondition().getStopDays());
//            params.getCondition().setEndDate(dateTime);
//        }

        //过滤权限
//        List<Long> powerCustomerShopIds = userService.getPowerCustomerShopIds();
        List<Long> powerCustomerShopIds = userService.getOneselfPowerCustomerShopIds();
        if (ObjectUtil.isNotEmpty(powerCustomerShopIds)) {
            if (!powerCustomerShopIds.contains(0L)) {
                YkfCustomerShopEntity condition = params.getCondition();
                if (ObjectUtil.isNull(params.getCondition())) {
                    condition = new YkfCustomerShopEntity();
                }
                condition.setPowerShopIds(powerCustomerShopIds);
                params.setCondition(condition);
            }
        } else {
            return new PageUtils();
        }

        IPage<YkfCustomerShopEntity> shopPage = shopDao.getStopPage(page, params.getSort(), ObjectUtil.isEmpty(params.getCondition()) ? new YkfCustomerShopEntity() : params.getCondition());
        PageUtils pageUtils = new PageUtils(shopPage);
        return pageUtils;
    }

    @Override
    public PageUtils getHistoricalShop(ParamsModel<YkfCustomerShopEntity> params) {
        // 分页对象
        IPage<YkfCustomerShopEntity> page = new Query<YkfCustomerShopEntity>().getPage(BeanUtil.beanToMap(params.getPage()));
        List<Long> powerCustomerShopIds = userService.getOneselfPowerCustomerShopIds();
        if (ObjectUtil.isNotEmpty(powerCustomerShopIds)) {
            if (!powerCustomerShopIds.contains(0L)) {
                YkfCustomerShopEntity condition = params.getCondition();
                if (ObjectUtil.isNull(params.getCondition())) {
                    condition = new YkfCustomerShopEntity();
                }
                condition.setPowerShopIds(powerCustomerShopIds);
                params.setCondition(condition);
            }
        } else {
            return new PageUtils();
        }
        IPage<YkfCustomerShopEntity> shopPage = shopDao.getHistoricalShop(page, params.getSort(), ObjectUtil.isEmpty(params.getCondition()) ? new YkfCustomerShopEntity() : params.getCondition());
        return new PageUtils(shopPage);
    }

    @Override
    public PageUtils selectPage(ParamsModel<YkfCustomerEntity> params) {
        QueryWrapper<YkfCustomerEntity> queryWrapper = ParamUtils.createQueryWrapperByDefaultSort(params);
        IPage<YkfCustomerEntity> page = this.page(
                new Query<YkfCustomerEntity>().getPage(BeanUtil.beanToMap(params.getPage())),
                queryWrapper
        );
        return new PageUtils(page);
    }

    @Override
    public void customerManagement(ExcelReq req, HttpServletResponse response) throws IOException {
        //查询列表
        ParamsModel<YkfCustomerShopEntity> params = new ParamsModel<>();
        params.setCondition(req.getCondition(new TypeReference<YkfCustomerShopEntity>() {
        }));
        params.setSort(req.getSort());
        ParamsModel.PageParams pageParams = new ParamsModel.PageParams();
        pageParams.setIndex(1L);
        pageParams.setSize(9999L);
        params.setPage(pageParams);
        PageUtils pageUtils = queryPage(params);
        List<CustomerManagementExcel> list = new ArrayList<>();
        if (ObjectUtil.isNotEmpty(pageUtils) && ObjectUtil.isNotEmpty(pageUtils.getList())) {
            for (Object o : pageUtils.getList()) {
                YkfCustomerEntity item = (YkfCustomerEntity) o;
                if (ObjectUtil.isNotEmpty(item.getBodyList())) {
                    for (YkfCustomerEntity customer : item.getBodyList()) {
                        if (ObjectUtil.isNotEmpty(customer.getShopList())) {
                            for (YkfCustomerShopEntity shopEntity : customer.getShopList()) {
                                CustomerManagementExcel excel = new CustomerManagementExcel();
                                BeanUtil.copyProperties(shopEntity, excel);
//                                excel.setCustomerNo(item.getCustomerNo());
                                excel.setCustomerName(item.getCustomerName());
                                excel.setExcludingRefunds(ObjectUtil.isNotEmpty(shopEntity.getExcludingRefunds()) ? (shopEntity.getExcludingRefunds() == 1 ? "是" : "否") : "");
                                excel.setServiceShiftName(dictDetailService.getDictName("serviceShift", shopEntity.getServiceShiftNo()));
                                excel.setFitRatioName(dictDetailService.getDictName("fitRatio", shopEntity.getFitRatioNo()));
                                list.add(excel);
                            }
                        }
                    }
                }
            }
        }
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("客户店铺", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        HorizontalCellStyleStrategy horizontalCellStyleStrategy =
                new HorizontalCellStyleStrategy(ExcelStyleUtils.getHeadStyle(), ExcelStyleUtils.getContentStyle());
        ExcelCellWidthStyleStrategy widthStyleStrategy = new ExcelCellWidthStyleStrategy();
        EasyExcel.write(response.getOutputStream(), CustomerManagementExcel.class)
                .sheet("客户店铺")
                .registerWriteHandler(horizontalCellStyleStrategy)
                .registerWriteHandler(widthStyleStrategy)
//                .registerWriteHandler(new CustomCellWriteHeightConfig())
//                .registerWriteHandler(new CustomCellWriteWidthConfig())
                .doWrite(list);
    }

    @Override
    public List<CommissionModel> shopBenefitDetail(YkfCustomerShopEntity params) {
        return inputRecordService.commissionCheckForShop(params);
    }

    @Override
    public Map<String, List<YkfCustomerShopEntity>> groupShopInfo(YkfCustomerEntity param) {
        LinkedHashMap<String, List<YkfCustomerShopEntity>> map = new LinkedHashMap<>();
        //查询所有店铺
        YkfCustomerShopEntity shop = new YkfCustomerShopEntity();
        Long customerId = param.getCustomerId();
        List<Long> customerIds = new ArrayList<>();
        customerIds.add(customerId);
        shop.setCustomerIds(customerIds);
        shop.setCooperateStatus(1);
        List<YkfCustomerShopEntity> shopList = shopDao.getShopList(shop, null);
        if (ObjectUtil.isNotEmpty(shopList)) {
            //未分组
            List<YkfCustomerShopEntity> unGroupList = shopList.stream().filter(o -> ObjectUtil.isNotEmpty(o.getFeeModel()) && o.getFeeModel() == 0 && StrUtil.isBlank(o.getMergeGroup())).collect(Collectors.toList());
            map.put("待分配", unGroupList);
            //已分组
            List<YkfCustomerShopEntity> groupedList = shopList.stream().filter(o -> ObjectUtil.isNotEmpty(o.getFeeModel()) && o.getFeeModel() == 0 && StrUtil.isNotBlank(o.getMergeGroup())).collect(Collectors.toList());
            if (!groupedList.isEmpty()) {
                Map<String, List<YkfCustomerShopEntity>> collect = groupedList.stream().collect(Collectors.groupingBy(YkfCustomerShopEntity::getMergeGroup));
                for (String group : collect.keySet()) {
                    map.put(group, collect.get(group));
                }
            }
            //单独收费
            List<YkfCustomerShopEntity> noGroupList = shopList.stream().filter(o -> ObjectUtil.isNotEmpty(o.getFeeModel()) && o.getFeeModel() == 1).collect(Collectors.toList());
            map.put("单独收费", noGroupList);
        }
        return map;
    }

    @Override
    public List<String> groupList(YkfCustomerEntity param) {
        List<String> resList = new ArrayList<>();
        //查询所有店铺
        YkfCustomerShopEntity shop = new YkfCustomerShopEntity();
        Long customerId = param.getCustomerId();
        List<Long> customerIds = new ArrayList<>();
        customerIds.add(customerId);
        shop.setCustomerIds(customerIds);
        shop.setCooperateStatus(1);
        List<YkfCustomerShopEntity> shopList = shopDao.getShopList(shop, null);
        if (ObjectUtil.isNotEmpty(shopList)) {
            resList = shopList.stream().map(YkfCustomerShopEntity::getMergeGroup).filter(StrUtil::isNotBlank).distinct().collect(Collectors.toList());
        }
        return resList;
    }

    @Override
    public void dispatchGroup(YkfCustomerEntity param) {
        UpdateWrapper<YkfCustomerShopEntity> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda().in(YkfCustomerShopEntity::getShopId, param.getShopIds())
                .set(YkfCustomerShopEntity::getMergeGroup, param.getMergeGroup());
        QueryWrapper<YkfCustomerShopEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(YkfCustomerShopEntity::getCustomerId, param.getCustomerId())
                .eq(YkfCustomerShopEntity::getMergeGroup, param.getMergeGroup());
        if (ObjectUtil.isNotEmpty(param.getBaseSalary())) {
            //查询分组是否存在
            if (customerShopService.count(queryWrapper) > 0) {
                throw new RRException("合并分组名称:" + param.getCustomerName() + "已存在,请检查");
            }
            updateWrapper.lambda().set(YkfCustomerShopEntity::getBaseSalary, param.getBaseSalary());
        } else {
            //查询已有分组的底薪
            queryWrapper.last("limit 1");
            YkfCustomerShopEntity one = customerShopService.getOne(queryWrapper);
            if (ObjectUtil.isNotEmpty(one)) {
                updateWrapper.lambda().set(YkfCustomerShopEntity::getBaseSalary, one.getBaseSalary());
            }
        }
        customerShopService.update(updateWrapper);
    }

    @Override
    public void storeChurnRegistration(ExcelReq req, HttpServletResponse response) throws IOException {
        //查询列表
        ParamsModel<YkfCustomerShopEntity> params = new ParamsModel<>();
        params.setCondition(req.getCondition(new TypeReference<YkfCustomerShopEntity>() {
        }));
        params.setSort(req.getSort());
        ParamsModel.PageParams pageParams = new ParamsModel.PageParams();
        pageParams.setIndex(1L);
        pageParams.setSize(9999L);
        params.setPage(pageParams);
        params.getCondition().setCooperateStatus(0);
        PageUtils pageUtils = queryStopPage(params);
        List<YkfCustomerShopEntity> dataList = (List<YkfCustomerShopEntity>) pageUtils.getList();
        List<YkfStopCustomerShopExcel> excelList = new ArrayList<>();
        if (ObjectUtil.isNotEmpty(dataList)) {
            if (ObjectUtil.isNotEmpty(dataList)) {
                for (YkfCustomerShopEntity shop : dataList) {
                    YkfStopCustomerShopExcel excel = new YkfStopCustomerShopExcel();
                    BeanUtil.copyProperties(shop, excel);
                    excelList.add(excel);
                }
            }
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("店铺流失登记", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            HorizontalCellStyleStrategy horizontalCellStyleStrategy =
                    new HorizontalCellStyleStrategy(ExcelStyleUtils.getHeadStyle(), ExcelStyleUtils.getContentStyle());
            ExcelCellWidthStyleStrategy widthStyleStrategy = new ExcelCellWidthStyleStrategy();
            EasyExcel.write(response.getOutputStream(), YkfStopCustomerShopExcel.class)
                    .sheet("店铺流失登记")
                    .registerWriteHandler(horizontalCellStyleStrategy)
                    .registerWriteHandler(widthStyleStrategy)
                    .doWrite(excelList);
        }
    }

    @Override
    public void customerHistoricalData(ExcelReq req, HttpServletResponse response) throws IOException {
        //查询列表
        ParamsModel<YkfCustomerShopEntity> params = new ParamsModel<>();
        params.setCondition(req.getCondition(new TypeReference<YkfCustomerShopEntity>() {
        }));
        params.setSort(req.getSort());
        ParamsModel.PageParams pageParams = new ParamsModel.PageParams();
        pageParams.setIndex(1L);
        pageParams.setSize(9999L);
        params.setPage(pageParams);
        params.getCondition().setCooperateStatus(0);
        PageUtils pageUtils = getHistoricalShop(params);
        List<YkfCustomerShopEntity> dataList = (List<YkfCustomerShopEntity>) pageUtils.getList();
        List<YkfHistoricalDataExcel> excelList = new ArrayList<>();
        if (ObjectUtil.isNotEmpty(dataList)) {
            if (ObjectUtil.isNotEmpty(dataList)) {
                for (YkfCustomerShopEntity shop : dataList) {
                    YkfHistoricalDataExcel excel = new YkfHistoricalDataExcel();
                    BeanUtil.copyProperties(shop, excel);
                    excelList.add(excel);
                }
            }
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("历史客户信息", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            HorizontalCellStyleStrategy horizontalCellStyleStrategy =
                    new HorizontalCellStyleStrategy(ExcelStyleUtils.getHeadStyle(), ExcelStyleUtils.getContentStyle());
            ExcelCellWidthStyleStrategy widthStyleStrategy = new ExcelCellWidthStyleStrategy();
            EasyExcel.write(response.getOutputStream(), YkfHistoricalDataExcel.class)
                    .sheet("历史客户信息")
                    .registerWriteHandler(horizontalCellStyleStrategy)
                    .registerWriteHandler(widthStyleStrategy)
                    .doWrite(excelList);
        }
    }

    @Override
    public void customerBenefitInquiry(ExcelReq req, HttpServletResponse response) throws IOException {
        //查询列表
        ParamsModel<YkfCustomerShopEntity> params = new ParamsModel<>();
        params.setCondition(req.getCondition(new TypeReference<YkfCustomerShopEntity>() {
        }));
        params.setSort(req.getSort());
        ParamsModel.PageParams pageParams = new ParamsModel.PageParams();
        pageParams.setIndex(1L);
        pageParams.setSize(9999L);
        params.setPage(pageParams);
        PageUtils pageUtils = shopBenefitPage(params);
        List<YkfCustomerEntity> dataList = (List<YkfCustomerEntity>) pageUtils.getList();
        List<CustomerShopBenefitExcel> excelList = new ArrayList<>();
        if (ObjectUtil.isNotEmpty(dataList)) {
            for (YkfCustomerEntity customer : dataList) {
                List<YkfCustomerShopEntity> shopList = customer.getShopList();
                if (ObjectUtil.isNotEmpty(shopList)) {
                    for (YkfCustomerShopEntity shop : shopList) {
                        CustomerShopBenefitExcel excel = new CustomerShopBenefitExcel();
                        BeanUtil.copyProperties(shop, excel);
                        excelList.add(excel);
                    }
                }
            }
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("客服效益查询", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            HorizontalCellStyleStrategy horizontalCellStyleStrategy =
                    new HorizontalCellStyleStrategy(ExcelStyleUtils.getHeadStyle(), ExcelStyleUtils.getContentStyle());
            ExcelCellWidthStyleStrategy widthStyleStrategy = new ExcelCellWidthStyleStrategy();
            EasyExcel.write(response.getOutputStream(), CustomerShopBenefitExcel.class)
                    .sheet("客服效益查询")
                    .registerWriteHandler(horizontalCellStyleStrategy)
                    .registerWriteHandler(widthStyleStrategy)
                    .doWrite(excelList);
        }
    }

    @Override
    public Map<String, Object> customerLvlInfo(YkfCustomerShopEntity params) {
        YkfCustomerShopEntity record = customerShopService.getById(params.getShopId());
        LinkedHashMap<String, Object> resMap = new LinkedHashMap<>();
        resMap.put("店铺名称", "");
        resMap.put("店铺类型", "");
        resMap.put("店铺难度得分", "0");
        resMap.put("服务天数", "");
        resMap.put("服务天数得分", "0");
        resMap.put("配合度", "");
        resMap.put("配合度得分", "0");
        resMap.put("上个服务周期开始时间", "");
        resMap.put("上个服务周期截止时间", "");
        resMap.put("上个服务周期总效益", "");
        resMap.put("上个服务周期总接待人数", "");
        resMap.put("上个服务周期日均接待人数", "");
        resMap.put("上个服务周期效益占比", "");
        resMap.put("效益得分", "0");
        resMap.put("总分", "0");
        resMap.put("总评", "D");
        if (ObjectUtil.isNotEmpty(record)) {
            resMap.put("店铺名称", record.getShopName());
            resMap.put("店铺类型", record.getShopTypeNo());
            //计算客户等级
            int score1 = 0;
            int score2 = 0;
            int score3 = 0;
            int score4 = 0;
            //店铺难度得分
            String shopTypeName = record.getShopTypeName();
            if (StrUtil.isNotBlank(shopTypeName)) {
                if (shopTypeName.contains("简单")) {
                    score1 = 24;
                } else if (shopTypeName.contains("普通")) {
                    score1 = 18;
                } else if (shopTypeName.contains("困难")) {
                    score1 = 12;
                } else if (shopTypeName.contains("噩梦")) {
                    score1 = 6;
                }
            }
            resMap.put("店铺难度得分", score1);
            //服务天数得分
            if (ObjectUtil.isNotEmpty(record.getStartDate())) {
                Date start = record.getStartDate();
                DateTime date = DateUtil.date();
                if (start.compareTo(date) < 0) {
                    long days = DateUtil.betweenDay(start, date, false);
                    if (days >= 180) {
                        score2 = 24;
                    } else if (days >= 90) {
                        score2 = 18;
                    } else if (days >= 60) {
                        score2 = 12;
                    } else if (days >= 30) {
                        score2 = 6;
                    }
                    resMap.put("服务天数", days);
                    resMap.put("服务天数得分", score2);
                }
            }

            //配合度得分
            if (StrUtil.isNotBlank(record.getFitRatioNo())) {
                switch (record.getFitRatioNo()) {
                    case "D":
                        score3 = 12;
                        break;
                    case "C":
                        score3 = 9;
                        break;
                    case "B":
                        score3 = 6;
                        break;
                    case "A":
                        score3 = 3;
                        break;
                }
                resMap.put("配合度", record.getFitRatioName());
                resMap.put("配合度得分", score3);
            }
            //效益得分 上个服务开始时间 上个服务结束时间 上个服务周期总收益 上个服务周期总接待人数 上个服务周期日均接待人数 上个服务周期效益占比
            if (ObjectUtil.isNotEmpty(record.getStartDate())) {
                DateTime end = DateUtil.offsetDay(record.getStartDate(), -1);
                DateTime start = DateUtil.offsetDay(end, -30);
                resMap.put("上个服务周期开始时间", DateUtil.formatDate(start));
                resMap.put("上个服务周期截止时间", DateUtil.formatDate(end));
                Map<String, BigDecimal> map = shopBenefit(start, end, record);
                BigDecimal sumSalary = map.get("sumSalary");
                BigDecimal sumReceptionVolume = map.get("sumReceptionVolume");
                BigDecimal averageReceptionVolume = map.get("averageReceptionVolume");
                List<YkfDictDetailEntity> dayRnumRatio = searchDictDetail("dayRnumRatio");
                resMap.put("上个服务周期总效益", sumSalary);
                resMap.put("上个服务周期总接待人数", sumReceptionVolume);
                resMap.put("上个服务周期日均接待人数", averageReceptionVolume);
                try {
                    if (ObjectUtil.isNotEmpty(dayRnumRatio)) {
                        BigDecimal value = BigDecimal.ONE;
                        for (YkfDictDetailEntity detail : dayRnumRatio) {
                            List<String> split = StrUtil.split(detail.getName(), '-');
                            if (split.size() == 2) {
                                BigDecimal decimal1 = new BigDecimal(split.get(0));
                                BigDecimal decimal2 = new BigDecimal(split.get(1));
                                if (averageReceptionVolume.compareTo(decimal1) >= 0
                                        && averageReceptionVolume.compareTo(decimal2) <= 0) {
                                    value = new BigDecimal(detail.getVal());
                                    break;
                                }
                            }
                        }
                        //计算上个服务效益占比
                        BigDecimal divide = sumSalary.multiply(new BigDecimal(100)).divide(value, 0, RoundingMode.HALF_DOWN);
                        resMap.put("上个服务周期效益占比", divide.toString() + "%");
                        List<YkfDictDetailEntity> benefitRatio = searchDictDetail("benefitRatio");
                        if (ObjectUtil.isNotEmpty(benefitRatio)) {
                            benefitRatio.sort(Comparator.comparing(YkfDictDetailEntity::getVal).reversed());
                            for (YkfDictDetailEntity detail : benefitRatio) {
                                if (StrUtil.equals(detail.getVal(), "160") && divide.compareTo(new BigDecimal(detail.getVal())) >= 0) {
                                    score4 = 40;
                                }
                                if (StrUtil.equals(detail.getVal(), "130") && divide.compareTo(new BigDecimal(detail.getVal())) >= 0) {
                                    score4 = 20;
                                }
                                if (StrUtil.equals(detail.getVal(), "100") && divide.compareTo(new BigDecimal(detail.getVal())) >= 0) {
                                    score4 = 10;
                                }
                                if (StrUtil.equals(detail.getVal(), "0") && divide.compareTo(new BigDecimal(detail.getVal())) >= 0) {
                                    score4 = 5;
                                }
                                resMap.put("效益得分", score4);
                            }
                        }
                    }
                } catch (Exception e) {
                    log.error(e.getMessage());
                }
            }
            int sumScore = score1 + score2 + score3 + score4;
            if (sumScore >= 80) {
                record.setCustomerLvl("A");
            } else if (sumScore >= 60) {
                record.setCustomerLvl("B");
            } else if (sumScore >= 40) {
                record.setCustomerLvl("C");
            } else {
                record.setCustomerLvl("D");
            }
            resMap.put("总分", sumScore);
            resMap.put("总评", record.getCustomerLvl());
        }
        return resMap;
    }

}
